import React, { useEffect, useState } from 'react';
import { Select } from 'tdesign-react';
import { JupiterDictionary } from '../../types/dictionaryTypes';
import { fetchActiveDictionariesByType } from '../../services/dictionaryService';

const { Option } = Select;

export interface DictionarySelectProps {
  dictType: string;
  value?: string;
  onChange?: (value: string) => void;
  placeholder?: string;
  clearable?: boolean;
  style?: React.CSSProperties;
  disabled?: boolean;
}

export default function DictionarySelect({
  dictType,
  value,
  onChange,
  placeholder,
  clearable = true,
  style,
  disabled = false,
}: DictionarySelectProps) {
  const [dictionaries, setDictionaries] = useState<JupiterDictionary[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (dictType) {
      fetchDictionaries();
    }
  }, [dictType]);

  const fetchDictionaries = async () => {
    setLoading(true);
    try {
      const response = await fetchActiveDictionariesByType(dictType);
      if (response.data) {
        // 按排序顺序排序
        const sortedDictionaries = response.data.sort((a: JupiterDictionary, b: JupiterDictionary) => a.sortOrder - b.sortOrder);
        setDictionaries(sortedDictionaries);
      }
    } catch (error) {
      console.error(`获取字典类型 ${dictType} 失败:`, error);
    } finally {
      setLoading(false);
    }
  };

  // Adapt onChange to tdesign-react Select signature
  const handleChange = (val: any, context: any) => {
    if (onChange) {
      onChange(String(val));
    }
  };

  return (
    <Select
      value={value}
      onChange={handleChange}
      placeholder={placeholder}
      clearable={clearable}
      style={style}
      disabled={disabled}
      loading={loading}
    >
      {dictionaries.map((dict) => (
        <Option key={dict.uuid} value={dict.dictKey} label={dict.dictLabel}>
          {dict.dictLabel}
        </Option>
      ))}
    </Select>
  );
}
